package com.rfid.rfidbluetooth.manager;

import android.content.SharedPreferences;

import androidx.preference.PreferenceManager;

import com.rfid.rfidbluetooth.App;
import com.rfid.rfidbluetooth.CmdBuild;
import com.rfid.rfidbluetooth.Rfid;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

public enum  ToServerManager {

    INSTANCE;

    Socket mSocket;
    OutputStream mOutputStream;

    public static String ip = "61.129.70.172";
    public static int port = 9993;

    public void init(){
        if (mSocket != null) {
            try {
                mOutputStream.close();
                mSocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(App.app);
            String ip1 = sharedPrefs.getString("ip",ip);
            String port1 = sharedPrefs.getString("port",port + "");
            System.out.println(ip1 + ":" + port1);
            boolean send = sharedPrefs.getBoolean("switch",false);
            System.out.println("send = " + send);
            mSocket = new Socket(ip1,Integer.valueOf(port1));
            mOutputStream = mSocket.getOutputStream();
            EventBus.getDefault().post("连接成功：" + ip1 + ":" + port1);
        } catch (Exception e) {
            e.printStackTrace();
            EventBus.getDefault().post(e.getMessage());
        }
    }

    public void send(List<Rfid> rfids){
        try{
            if (mOutputStream != null) {
                byte data[] = CmdBuild.sendEpcs(rfids);
                mOutputStream.write(data);
            } else {
                init();
            }
        } catch (Exception e) {
            e.printStackTrace();
            mOutputStream = null;
            init();
        }
    }

    public void send(byte data[]) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(App.app);
        boolean send = sharedPrefs.getBoolean("switch",false);
        if (!send) {
            return;
        }
        try{
            if (mOutputStream != null) {
                mOutputStream.write(data);
                EventBus.getDefault().post("发送数据到服务器成功");
            } else {
                init();
            }
        } catch (Exception e) {
            e.printStackTrace();
            EventBus.getDefault().post(e.getMessage());
            mOutputStream = null;
            init();
        }
    }


}
